<?php
namespace WebApper;
/*
 * [emailimport]
 *
 */
class EmailImport extends  \WebApper\Shortcode {
	/**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'emailimport';
	
	/**
     * Initialize the Shortcode Class
     *
     */
	public function __construct() {
		add_shortcode( $this->shortcode, array($this, 'shortcode') );
		add_action( 'wp_ajax_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );
		add_action( 'wp_ajax_nopriv_web_apper' . $this->shortcode, array($this, 'sendAjaxResponse') );	
				
		/*if ( ! wp_next_scheduled( 'my_daily_email_import' ) )
		{
			wp_schedule_event( time() , 'every5mins', 'my_daily_email_import');			
		}	
		add_action( 'my_daily_email_import', array($this, 'shortcode') );*/	
	}

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {
		// Check for required shortcode attributes
		$msg = $this->has_req_attrs( $atts );
		if ( $msg !== true )
			return $msg;			
		$userID = get_current_user_id();
		$user_setting = get_user_meta($userID); 
		//print_r($user_setting);
		//return false;
		$userName = $user_setting['emailAddress'][0];  //'jesse@azrto.info';
		$userEmailName = $user_setting['emailUserName'][0];
		
		//echo $userEmailName;
		$password = $user_setting['emailPassword'][0];   //'jesse';
		$server = $user_setting['emailServer'][0]; //'azrto.info';
		$port = $user_setting['emailPort'][0];//993;
		$ssl = $user_setting['emailSSL'][0];   
		
		/*Ex: For Gmail
		$userName = 'XXXX@gmail.com';
		$password = 'XXX';
		$server = 'imap.gmail.com';
		$port = 993;
		$ssl = true;*/
		global $wpdb, $webapper;
		$table = $webapper->tables->emails;
		$user_ID = get_current_user_id()==0 ? 7:get_current_user_id();
		$tableAttachment = $webapper->tables->email_attachments;
		$lastReceivedDate = $wpdb->get_results("SELECT date_on FROM $table WHERE `to`='$userName' and  user_id='$user_ID' ORDER BY date_on DESC limit 0,1" );
		$filePath = WEB_APPER_DIR_PATH . "email_attachments";
		$get_posts_args = array( 'post_type' => 'lead', 'order'=> 'ASC', 'orderby' => 'title', 'posts_per_page' => -1 );  // Set query arguments
		$customPostObjs = get_posts( $get_posts_args );
		$objMailLib = new MailLib();
		$connect = $objMailLib->connect($userName, $password, $server, $port, $ssl);
		$getIds = array();
		if($connect):
			$getIds = $objMailLib->getMails();			
			foreach($getIds as $id):
				$emailDetails = $objMailLib->getMail($id);	
				$isAttachment = $emailDetails['attachments']==''?'N':'Y';
				if( count($lastReceivedDate) ==0)
				{					
					$tagValue = "";
					foreach($customPostObjs as $post)
					{
						$priEmail = get_post_meta( $post->ID, 'email-primary', true );
						if($emailDetails['sender'] == $priEmail )
						{
							$tagValue = $post->post_title;
							break;
						}						 
					}					
					$sql = $wpdb->prepare( "INSERT INTO {$table} ( user_id, `to`, to_name, `from`, from_name, subject, message_body, attachment_path, label, tag, date_on ) VALUES ( %d,%s, %s, %s, %s, %s, %s, %s, %s, %s,%d )", $user_ID, $emailDetails['recipient'], $emailDetails['recipientName'], $emailDetails['sender'], $emailDetails['senderName'], $emailDetails['subject'], $emailDetails['body'], $isAttachment, 'Inbox' , $tagValue, $emailDetails['date'] );									
					$result = $wpdb->query( $sql );					
					if ( $result )
					{
						$lastId = $wpdb->insert_id;
						if($isAttachment == 'Y')
						{
							$files = $emailDetails['attachments'];
							foreach($files as $file)
							{
								if(!is_dir($filePath . "/"))
								{
									mkdir($filePath . "/" , 0777);
									chmod($filePath . "/" , 0777);
								}
								if(!is_dir($filePath . "/" . $lastId))
								{
									mkdir($filePath . "/" . $lastId ."/", 0777);
									chmod($filePath . "/" . $lastId ."/", 0777);
								}
								$maxId = $wpdb->get_results("SELECT ifnull(MAX(ID),0)+1 AS ID FROM $tableAttachment");
								$fileType = wp_check_filetype($file);
								$tempFileName = $maxId[0]->ID.".".$fileType['ext'];
								$sqlAttach = $wpdb->prepare( "INSERT INTO {$tableAttachment} ( emails_id, file_path, file_name ) VALUES ( %d, %s, %s)", $lastId, $tempFileName, $file );
								$resultAttach = $wpdb->query( $sqlAttach );
								$path = $filePath . "/" . $lastId ."/" .$tempFileName;
								$content = $objMailLib->getAttachment($file, $id);
								file_put_contents($path, $content);	
							}
						}						
						echo "Success: ".$emailDetails['sender']."<br />";
					}
				}
				else
				{
					if($emailDetails['date'] >$lastReceivedDate[0]->date_on)
					{
						$tagValue = "";
						foreach($customPostObjs as $post)
						{
							$priEmail = get_post_meta( $post->ID, 'email-primary', true );
							if($emailDetails['sender'] == $priEmail )
							{
								$tagValue = $post->post_title;
								break;
							}						 
						}
						
						$sql = $wpdb->prepare( "INSERT INTO {$table} ( user_id, `to`, to_name, `from`, from_name, subject, message_body, attachment_path, label, tag, date_on ) VALUES ( %d ,%s, %s, %s, %s, %s, %s, %s, %s, %s, %d )", $user_ID, $emailDetails['recipient'], $emailDetails['recipientName'], $emailDetails['sender'], $emailDetails['senderName'], $emailDetails['subject'], $emailDetails['body'], $isAttachment, 'Inbox', $tagValue, $emailDetails['date'] );
						$result = $wpdb->query( $sql );
						if ( $result )
						{
							$lastId = $wpdb->insert_id;
							if($isAttachment == 'Y')
							{
								$files = $emailDetails['attachments'];
								foreach($files as $file)
								{
									if(!is_dir($filePath . "/"))
									{
										mkdir($filePath . "/" , 0777);
										chmod($filePath . "/" , 0777);
									}
									if(!is_dir($filePath . "/" . $lastId))
									{
										mkdir($filePath . "/" . $lastId ."/", 0777);
										chmod($filePath . "/" . $lastId ."/", 0777);
									}
									$maxId = $wpdb->get_results("SELECT ifnull(MAX(ID),0)+1 AS ID FROM $tableAttachment");
									$fileType = wp_check_filetype($file);
									$tempFileName = $maxId[0]->ID.".".$fileType['ext'];
									$sqlAttach = $wpdb->prepare( "INSERT INTO {$tableAttachment} ( emails_id, file_path, file_name ) VALUES ( %d, %s, %s)", $lastId, $tempFileName, $file );
									$resultAttach = $wpdb->query( $sqlAttach );
									$path = $filePath . "/" . $lastId ."/" .$tempFileName;
									$content = $objMailLib->getAttachment($file, $id);
									file_put_contents($path, $content);	
								}
							}
							echo "Success: ".$emailDetails['sender']."<br />";
						}
					}
					else
					{
						break;						
					}
				}
			endforeach;			 
		else:
			echo "Cannot connect to mail server. Try again!";
		endif;
	}
}
$initialize = new EmailImport(); 
?>